package ftp.action;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import fpt.dao.FtpConfiglangDAO;
import fpt.dao.FtpConnectSQLITE;
import fpt.dao.FtpUserDAO;
import fpt.util.FTPUtil;
import fpt.util.UtilInitLang;
import ftp.pojo.FtpConfiglang;
import ftp.pojo.FtpConnect;
import ftp.pojo.FtpUser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.commons.net.ftp.*;

public class FtpClientActivity extends Activity {
	class PInfo {
		private String appname = "";
		@SuppressWarnings("unused")
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
	}
	public int co=0;
	EditText username,pass,port;
	private Bundle alllangs = new Bundle();
	String typeLang = "EN";
	UtilInitLang utilang = new UtilInitLang();
	private boolean read = true;
	ImageView imageVN,imageEN,imageKR;
	CheckBox checkpass;
	FtpUser emp = new FtpUser();
	public FTPClient mFTPClient = null;
	FtpConnect ftp=new FtpConnect();
	FtpConnect lastconnect= new FtpConnect();
	Button btLogin;
	String host="";

	Bundle lang= new Bundle();

	//auto update
	public int VersionCode;
	public String VersionName="";
	public String ApkName ;
	public String AppName ;
	public String BuildVersionPath="";
	public String urlpath ;
	public String PackageName;
	public String InstallAppPackageName;
	public String Text="";


	// TODO hongmophi
	private Spinner lstSpinnerHost;
	private List<FtpConnect> lstConnect = new ArrayList<FtpConnect>();
	ArrayAdapter<FtpConnect> adapter;
	private FtpConnectSQLITE ftpConnectSQLITE;

	public  String ahostname="";
	public  String aport="";
	public  String ausername="";
	public  String apassword="";


	public static boolean flagChangeViewDownload = false;
	public static boolean flagChangeViewUpload = false;

	int screenheight,screenwidth;
	int flagcheckpass=1;

	//wait
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	TextView tvwaiting;
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Text= "New".toString();

		ApkName = "EliFTP.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //      
		AppName="Eli FTP";
		BuildVersionPath = "http://14.63.215.15/EliFTP/ftp_version.txt".toString();
		PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
		urlpath = "http://14.63.215.15/EliFTP/" + ApkName.toString();


		GetVersionFromServer(BuildVersionPath); 

		readFile();

		lang = this.getAlllangs().getBundle(typeLang);

		if(checkInstalledApp(AppName.toString()) == true)
		{   
			Toast.makeText(getApplicationContext(), lang.getString("appfound")+" " + AppName.toString(), Toast.LENGTH_SHORT).show();


		}else{
			Toast.makeText(getApplicationContext(), lang.getString("appnotfound")+" "+ AppName.toString(), Toast.LENGTH_SHORT).show();          

		}

		setContentView(R.layout.main);

		loadContent();
		
		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);


		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		btLogin.setOnClickListener(loginbtn);
		
	}


	public void loadContent(){
		ftpConnectSQLITE = new FtpConnectSQLITE(this);
		ftpConnectSQLITE.open();

		initAttribute();    
	}

	private OnClickListener loginbtn = new OnClickListener() {


		public void onClick(View v) {
			if(co==0){
				co=1;
				try{
					alertwaiting.show();
					try{
						new Thread(){
							public void run() {
								FTPUtil.HOST=host;
								FTPUtil.PORT=Integer.parseInt(port.getText().toString());
								FTPUtil.USER=username.getText().toString();
								FTPUtil.PASS=pass.getText().toString();
								final boolean kq=FTPUtil.connects();
								if (kq==true) {
									ftp.setHostname(host);
									ftp.setPort(port.getText().toString());
									ftp.setPassword(pass.getText().toString());
									ftp.setUsername(username.getText().toString());		

								}
								uiHandler.post( new Runnable(){
									@Override
									public void run() {
										if(isUpdateRequired){
											//TODO:
										}else{
											if (kq==true) {
												startActivity();
											} else {
												alertwaiting.cancel();
												openDialogError();
											}
										}
									}
								} );
							}

						}.start();
					}catch (Exception e) {}
				}catch (Exception e) {
					e.printStackTrace();
				} 
			}

		}

	}; 

	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle(lang.getString("warning"));
		builder.setMessage(lang.getString("rploginfail"));
		builder.setCancelable(false);
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	private void startActivity() {
		deletefile();
		writefileUpload();
		Intent ii = new Intent(this, MainActivity2.class);
		ii.putExtra("lang", typeLang);
		ii.putExtras(alllangs);		
		ii.putExtra("ftp", ftp);
		ii.putExtra("flagtab",0);
		alertwaiting.cancel();
		startActivity(ii);
	}

	public FtpUser checkLogin(String username, String pass) {
		FtpUserDAO lg = new FtpUserDAO();
		FtpUser emp = lg.checkLogin(username, pass);
		return emp;
	}
	public void initLangue(){

		lang = this.getAlllangs().getBundle(typeLang);
		TextView thost=(TextView)findViewById(R.id.host);
		thost.setText(lang.getString("hostname"));

		TextView tport=(TextView)findViewById(R.id.Port);
		tport.setText(lang.getString("port"));		

		TextView tendn = (TextView) findViewById(R.id.tendn);
		tendn.setText(lang.getString("username"));

		TextView pw = (TextView) findViewById(R.id.matkhau);
		pw.setText(lang.getString("password"));

		btLogin.setText(lang.getString("connect"));

		checkpass.setText(lang.getString("checkpass"));
	}
	public void initAttribute() {
		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		screenheight = displaymetrics.heightPixels;
		screenwidth = displaymetrics.widthPixels;

		TextView thost=(TextView)findViewById(R.id.host);
		thost.setText(lang.getString("hostname"));

		TextView tport=(TextView)findViewById(R.id.Port);
		tport.setText(lang.getString("port"));

		TextView t = (TextView) findViewById(R.id.tendn);
		t.setText(lang.getString("username"));

		TextView t2 = (TextView) findViewById(R.id.matkhau);
		t2.setText(lang.getString("password"));

		port = (EditText) findViewById(R.id.txtPort);
		username =(EditText)findViewById(R.id.userName);
		pass =(EditText)findViewById(R.id.pass);

		btLogin = (Button) findViewById(R.id.btLogin);
		btLogin.setText(lang.getString("connect"));

		lstSpinnerHost = (Spinner)findViewById(R.id.spinnerhost);
		lstConnect = ftpConnectSQLITE.getAllConnect();
		System.out.println(" lst connect == " + lstConnect.toString());

		rememberlastlogin();
		checkpass =(CheckBox)findViewById(R.id.checkpass);
		int wd=screenwidth/2;
		checkpass.setWidth(wd);
		checkpass.setText(lang.getString("checkpass"));


		if(!lastconnect.getHostname().equals("null")){
			for(int i=0;i<lstConnect.size();i++){
				if(lastconnect.getHostname().equals(lstConnect.get(i).getHostname())){
					lstConnect.set(i, lstConnect.get(0));
					lstConnect.set(0, lastconnect);
					System.out.println("ok ok ok");
					if(!lastconnect.getPassword().equals("null")){
						checkpass.setChecked(true);
						flagcheckpass=1;
					}else{
						checkpass.setChecked(false);
						flagcheckpass=2;
					}
					break;
				}
			}
		}

		adapter = new ArrayAdapter<FtpConnect>(this,android.R.layout.simple_spinner_dropdown_item,lstConnect);
		lstSpinnerHost.setAdapter(adapter);
		
		lstSpinnerHost.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction()==MotionEvent.ACTION_UP){
					if(lstConnect.size()==0){
							co = 1;
							AlertDialog.Builder builder = new AlertDialog.Builder(FtpClientActivity.this);
							builder.setTitle(lang.getString("notification"));
							builder.setMessage(lang.getString("questionnotifi"));
							
							builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									showpopupaddhostFromAndroid();
									dialog.dismiss();
								}
							});
							builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									
								}
							});
							final AlertDialog alertDialog = builder.create();
							alertDialog.show();
							
							return true;
						}
				}
				return false;
			}
		});

		lstSpinnerHost.setOnItemSelectedListener(processSpinner);	

		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaiting.setText(lang.getString("waiting")+"...");

		builderwaiting = new AlertDialog.Builder(FtpClientActivity.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();
	}


	private void readFile(){		

		try {
			File fr = getBaseContext().getFileStreamPath("user.txt");
			if(fr.exists()){
				Scanner scanner = new Scanner(fr);
				typeLang=scanner.next().trim();
				if(typeLang.equals("")){
					typeLang="EN";
				}
			}else{
				typeLang="EN";
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Bundle getAlllangs() {
		if (isRead()) {
			FtpConfiglangDAO lang = new FtpConfiglangDAO();
			Bundle resultVN = new Bundle();
			Bundle resultEN = new Bundle();
			Bundle resultKR = new Bundle();
			try {
				ArrayList<FtpConfiglang> arr = lang.allLang();
				for (int i = 0; i < arr.size(); i++) {
					resultVN.putString(arr.get(i).getIdkey(), arr.get(i).getVn());
					resultEN.putString(arr.get(i).getIdkey(), arr.get(i).getEn());
					resultKR.putString(arr.get(i).getIdkey(), arr.get(i).getKr());
				};
			} catch (Exception E) {
				E.printStackTrace();
			}
			alllangs.putBundle("VN", resultVN);
			alllangs.putBundle("EN", resultEN);
			alllangs.putBundle("KR", resultKR);
		}
		setRead(false);
		return alllangs;
	}

	public boolean isRead() {
		return read;
	}
	public void setRead(boolean read) {
		this.read = read;
	}

	public OnClickListener processImageVN = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "VN";
			try {
				writefile();
			} catch (Exception e) {
				e.printStackTrace();
			}
			initLangue();
		}
	};

	public OnClickListener processImageEN = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "EN";
			try {
				writefile();
			} catch (Exception e) {
				e.printStackTrace();
			}
			initLangue();
		}
	};

	public OnClickListener processImageKR = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "KR";
			try {
				writefile();
			} catch (Exception e) {
				e.printStackTrace();
			}
			initLangue();
		}
	};


	public OnItemSelectedListener processSpinner = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
			System.out.println(" vao day o");
			ftp = (FtpConnect)lstSpinnerHost.getItemAtPosition(arg2);
			System.out.println(" ftp == " + ftp.getHostname());
			host = ftp.getHostname();
			port.setText(ftp.getPort());
			username.setText(ftp.getUsername());
			System.out.println(" host == " + host);
			System.out.println(" port == " + port);
			System.out.println("username == " + username);
			if(flagcheckpass==1){
				pass.setText(ftp.getPassword());				
			}else{
				pass.setText("");
				flagcheckpass=1;
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			Log.d(getApplicationContext().getPackageName(), "Select Item :"
					+ "Nothing");
			typeLang = "EN";			
		}
	};

	protected void showPopupDelete() {
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle(lang.getString("titledelete"));
		helpBuilder.setMessage(lang.getString("deleteerror"));
		helpBuilder.setCancelable(false);
		helpBuilder.setPositiveButton(lang.getString("ok"),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				co=0;
				ftpConnectSQLITE.deleteFtp(ftp);
				Intent intent = new Intent(
						FtpClientActivity.this,
						FtpClientActivity.class);

				startActivity(intent);
				finish();
			}
		});

		helpBuilder.setNegativeButton(lang.getString("cancel"),
				new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				co=0;
			}
		});

		// Remember, create doesn't show the dialog
		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}

	
	private Boolean checkInstalledApp(String appName){
		return getPackages(appName);    
	}

	// Get Information about Only Specific application which is Install on Device.
	public String getInstallPackageVersionInfo(String appName) 
	{
		String InstallVersion = "";     
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
		Toast.makeText(getApplicationContext(), lang.getString("currenversion")+" : " + InstallVersion.toString(), Toast.LENGTH_LONG).show();

		return InstallVersion.toString();
	}
	private Boolean getPackages(String appName) 
	{
		Boolean isInstalled = false;
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{

			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				if(VersionCode <= apps.get(i).versionCode)
				{
					isInstalled = false;

				}    
				if(VersionCode > apps.get(i).versionCode)
				{
					isInstalled = true;

					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage(lang.getString("youareusingversion")+" "+getInstallPackageVersionInfo(AppName.toString()).toString()+". "+lang.getString("nownewversion")+ GetVersionFromServer(VersionName.toString()).toString()+ ". "+lang.getString("doyouwantinstall") +"?")
					.setPositiveButton(lang.getString("install"), dialogClickListener)
					.setNegativeButton(lang.getString("cancel"), dialogClickListener).show();              

				}
			}
		}




		return isInstalled;
	}
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) 
	{       
		ArrayList<PInfo> res = new ArrayList<PInfo>();        
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for(int i=0;i<packs.size();i++) 
		{
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue ;
			}
			PInfo newInfo = new PInfo();
			newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
			newInfo.pname = p.packageName;
			newInfo.versionName = p.versionName;
			newInfo.versionCode = p.versionCode;
			res.add(newInfo);
		}
		return res; 
	}


	public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
	{
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent); 
	}
	public void InstallApplication()
	{   
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);

		intent.setDataAndType
		(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"  + ApkName.toString())), "application/vnd.android.package-archive");
		startActivity(intent);  
	}
	public String GetVersionFromServer(String BuildVersionPath)
	{
		URL u;
		try {
			u = new URL(BuildVersionPath.toString());

			HttpURLConnection c = (HttpURLConnection) u.openConnection();           
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			InputStream in = c.getInputStream();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..

			int len1 = 0;
			while ( (len1 = in.read(buffer)) != -1 ) 
			{               
				baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
			}

			String temp = "";     
			String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;

			for (int i = 0; i < s.length(); i++)
			{               
				i = s.indexOf("=") + 1; 
				while (s.charAt(i) == ' ') // Skip Spaces
				{
					i++; // Move to Next.
				}
				while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
				{
					temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
					i++;
				}
				//
				s = s.substring(i); // Move to Next to Process.!
				temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
			}
			String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.

			VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
			VersionName = fields[1].toString();

			System.out.println("Vesiom code _ " + VersionCode);
			System.out.println("Vesion name _ " + VersionName);
			baos.close();
		}
		catch (MalformedURLException e) {
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {           
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		return VersionName;
	}// Method End.

	// Download On My Mobile SDCard or Emulator.
	public void DownloadOnSDcard()
	{
		try{
			URL url = new URL(urlpath.toString()); // Your given URL.

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect(); // Connection Complete here.!


			String PATH = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(PATH); // PATH = /mnt/sdcard/download/
			if (!file.exists()) {
				file.mkdirs();
			}
			File outputFile = new File(file, ApkName.toString());           
			FileOutputStream fos = new FileOutputStream(outputFile);

			InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1); // Write In FileOutputStream.
			}
			fos.close();
			is.close();//till here, it works fine - .apk is download to my sdcard in download file.
		} 
		catch (IOException e) 
		{
			Toast.makeText(getApplicationContext(), "Error! " +
					e.toString(), Toast.LENGTH_LONG).show();
		}           
	}

	// show popup add host
	public void showpopupaddhostFromAndroid(){
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.addhost, null);

		final EditText txtHostname = (EditText) textEntryView.findViewById(R.id.txtAddHost);
		txtHostname.setText(ahostname);
		final EditText txtPort = (EditText) textEntryView.findViewById(R.id.txtAddPort);
		txtPort.setText(aport);
		final EditText txtUserName = (EditText) textEntryView.findViewById(R.id.txtUserName);
		txtUserName.setText(ausername);
		final EditText txtPass = (EditText) textEntryView.findViewById(R.id.txtPass);
		txtPass.setText(apassword);
		final TextView hostname = (TextView) textEntryView.findViewById(R.id.addhostName);
		final TextView vport = (TextView) textEntryView.findViewById(R.id.aaPort);
		final TextView vus = (TextView) textEntryView.findViewById(R.id.addUsername);
		final TextView vps = (TextView) textEntryView.findViewById(R.id.addPass);

		hostname.setText(lang.getString("hostname"));
		vport.setText(lang.getString("port"));
		vus.setText(lang.getString("username"));
		vps.setText(lang.getString("password"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("addhost"));
		builder.setView(textEntryView);
		builder.setCancelable(false);
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					if(!txtHostname.getText().toString().equals("") && !txtPort.getText().toString().equals("")
							&& !txtUserName.getText().toString().equals("") && !txtPass.getText().toString().equals("")){
						ahostname="";
						aport="";
						ausername="";
						apassword="";

						ftpConnectSQLITE.createFtpConnect(txtHostname.getText().toString(), txtPort.getText().toString(), txtUserName.getText().toString(),
								txtPass.getText().toString());

						Intent intent = new Intent(FtpClientActivity.this, FtpClientActivity.class);
						startActivity(intent);
					}
					else if(txtHostname.getText().toString().equals("") || txtPort.getText().toString().equals("")
							|| txtUserName.getText().toString().equals("") || txtPass.getText().toString().equals("")){

						ahostname = txtHostname.getText().toString();
						aport = txtPort.getText().toString();
						ausername = txtUserName.getText().toString();
						apassword = txtPass.getText().toString();

						Toast.makeText(getApplicationContext(),lang.getString("isempty"), Toast.LENGTH_LONG).show();
						showpopupaddhostFromAndroid();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
				co=0;
			}
		}
		);
		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				co=0;
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	// edit host 
	public void showpopupedithostfromAdroid(){
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.edithost, null);

		final EditText txtHostname = (EditText) textEntryView.findViewById(R.id.txteditHost);
		txtHostname.setText(ahostname);
		final EditText txtPort = (EditText) textEntryView.findViewById(R.id.txteditPort);
		txtPort.setText(aport);
		final EditText txtUserName = (EditText) textEntryView.findViewById(R.id.txteditUserName);
		txtUserName.setText(ausername);
		final EditText txtPass = (EditText) textEntryView.findViewById(R.id.txteditPass);
		txtPass.setText(apassword);

		txtHostname.setText(ftp.getHostname());
		txtPort.setText(String.valueOf(ftp.getPort()));
		txtUserName.setText(ftp.getUsername());
		txtPass.setText(ftp.getPassword());

		final TextView hostname = (TextView) textEntryView.findViewById(R.id.edithostName);
		final TextView vport = (TextView) textEntryView.findViewById(R.id.editPort);
		final TextView vus = (TextView) textEntryView.findViewById(R.id.editUsername);
		final TextView vps = (TextView) textEntryView.findViewById(R.id.editPass);

		hostname.setText(lang.getString("hostname"));
		vport.setText(lang.getString("port"));
		vus.setText(lang.getString("username"));
		vps.setText(lang.getString("password"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("edithost"));
		builder.setView(textEntryView);
		builder.setCancelable(false);
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if( !txtHostname.getText().toString().equals("") && !txtPort.getText().toString().equals("")
						&& !txtUserName.getText().toString().equals("") && !txtPass.getText().toString().equals("")){
					ahostname ="";
					aport = "";
					ausername = "";
					apassword = "";

					ftp.setHostname(txtHostname.getText().toString());
					ftp.setPort(txtPort.getText().toString());
					ftp.setUsername(txtUserName.getText().toString());
					ftp.setPassword(txtPass.getText().toString());

					ftpConnectSQLITE.updateFtp(ftp);

					Intent intent = new Intent(FtpClientActivity.this, FtpClientActivity.class);
					startActivity(intent);
				}
				else if(txtHostname.getText().toString().equals("") || txtPort.getText().toString().equals("")
						|| txtUserName.getText().toString().equals("") || txtPass.getText().toString().equals("")){
					ahostname = txtHostname.getText().toString();
					aport = txtPort.getText().toString();
					ausername = txtUserName.getText().toString();
					apassword = txtPass.getText().toString();

					Toast.makeText(getApplicationContext(),lang.getString("isempty"), Toast.LENGTH_LONG).show();
					showpopupedithostfromAdroid();
				} 
				co=0;

			}
		});

		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				co=0;
			}
		});

		AlertDialog alert = builder.create();
		alert.show();	 
	}

	private void writefile() throws Exception{
		FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
		file.write(typeLang.getBytes());		
		file.close();
	}

	private void deletefile(){
		FileOutputStream file;
		try {
			String s="/";
			file = openFileOutput("download.txt", Context.MODE_PRIVATE);
			file.write(s.getBytes());		
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void writefileUpload(){
		FileOutputStream file;
		try {
			String s=Environment.getExternalStorageDirectory().toString();
			file = openFileOutput("upload.txt", Context.MODE_PRIVATE);
			file.write(s.getBytes());		
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void rememberlastlogin(){		

		try {
			File fr = getBaseContext().getFileStreamPath("lastlogin.txt");
			if(fr.exists()){
				Scanner scanner = new Scanner(fr);
				scanner.useDelimiter("-");
				lastconnect.setHostname(scanner.next().trim());
				lastconnect.setPort(scanner.next().trim());
				lastconnect.setUsername(scanner.next().trim());
				lastconnect.setPassword(scanner.next().trim());				
			}else{
				lastconnect.setHostname("");
				lastconnect.setPort("");
				lastconnect.setUsername("");
				lastconnect.setPassword("");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*private void writefilerememberlastlogin(){
		FileOutputStream file;
		try {
			file = openFileOutput("lastlogin.txt", Context.MODE_PRIVATE);
			file.write(ftp.getHostname().getBytes());	
			file.write("-".getBytes());
			file.write(ftp.getPort().getBytes());	
			file.write("-".getBytes());
			file.write(ftp.getUsername().getBytes());	
			file.write("-".getBytes());
			if(checkpass.isChecked()){
				file.write(ftp.getPassword().getBytes());
			}else
				file.write("null".getBytes());
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void writefilerememberlastloginnull(){
		FileOutputStream file;
		try {
			file = openFileOutput("lastlogin.txt", Context.MODE_PRIVATE);
			file.write("null".getBytes());	
			file.write("-".getBytes());
			file.write("null".getBytes());	
			file.write("-".getBytes());
			file.write("null".getBytes());	
			file.write("-".getBytes());
			file.write("null".getBytes());	
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(typeLang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu_en, menu);
		}else if(typeLang.equals("VN")){
			inflater.inflate(R.menu.option_main_menu_vn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menu_kr, menu);
		}

		setMenuBackground();
		return true;

	}
	
	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  


			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundColor(Color.parseColor("#506256"));
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(typeLang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menuaddhostvn:
				processAddHost();
				return true;
			case R.id.menuedithostvn:
				processEditHost();
				return true;
			case R.id.menudeletehostvn:
				processDeleteHost();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(typeLang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menuaddhostkr:
				processAddHost();
				return true;
			case R.id.menuedithostkr:
				processEditHost();
				return true;
			case R.id.menudeletehostkr:
				processDeleteHost();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menuaddhost:
				processAddHost();
				return true;
			case R.id.menuedithost:
				processEditHost();
				return true;
			case R.id.menudeletehost:
				processDeleteHost();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	}
	
	public void processAddHost(){
		if(co==0){
			co=1;
			showpopupaddhostFromAndroid();
		}
	}
	public void processEditHost(){
		if(co==0){
			co=1;
			showpopupedithostfromAdroid();
		}
	}
	public void processDeleteHost(){
		if(co==0){
			co=1;
			showPopupDelete();
		}
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("exitapp"));
		builder.setMessage(lang.getString("questionexitapp"));
		builder.setPositiveButton(lang.getString("ok"),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				FtpClientActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		
		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
}